import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:taonile/config/config.dart';

import '../routers/routers.dart';
import '../utils/singleton_manager.dart';

typedef PageChanged = void Function(int index);

class PhotoPreview extends StatefulWidget {
  final int defaultImage; //默认第几张
  final PageChanged? pageChanged; //切换图片回调

  const PhotoPreview({
    Key? key,
    this.defaultImage = 1,
    this.pageChanged,
  }) : super(key: key);

  @override
  State<PhotoPreview> createState() => _PhotoPreviewState();
}

class _PhotoPreviewState extends State<PhotoPreview> {
  List galleryItems = []; //图片列表
  late int tempSelect;

  @override
  void initState() {
    super.initState();
    galleryItems = SingletonManager.instance.galleryItems;
    tempSelect = widget.defaultImage + 1;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          PhotoViewGallery.builder(
              scrollPhysics: const BouncingScrollPhysics(),
              builder: (BuildContext context, int index) {
                return PhotoViewGalleryPageOptions(
                  imageProvider: NetworkImage(galleryItems[index]),
                );
              },
              scrollDirection: Axis.horizontal,
              itemCount: galleryItems.length,
              backgroundDecoration: const BoxDecoration(color: Colors.black),
              pageController: PageController(initialPage: widget.defaultImage),
              onPageChanged: (index) => setState(() {
                    tempSelect = index + 1;
                    if (widget.pageChanged != null) {
                      widget.pageChanged!(index);
                    }
                  })),
          Positioned(
            ///布局自己换
            right: 35.w,
            bottom: 30.w,
            child: Text(
              '$tempSelect/${galleryItems.length}',
              style: const TextStyle(color: Colors.white),
            ),
          ),
          Positioned(
            left: 30.w,
            top: 120.w,
            child: InkWell(
              onTap: () {
                Routes.router.pop(context);
              },
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Config.colorBg,
                  borderRadius: BorderRadius.circular(35.w),
                ),
                width: 70.w,
                height: 70.w,
                child: Icon(
                  Icons.close,
                  size: 45.w,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
